<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item label="工单名称">
        <div class="my-show-span">{{ form.workOrderName }}</div>
      </el-form-item>
      <el-form-item label="工单编号">
        <div class="my-show-span">{{ form.workOrderCode }}</div>
      </el-form-item>
      <el-form-item label="关联计划">
        <div class="my-show-span">{{ form.proSchedule ? form.proSchedule.scheduleName : '' }}</div>
      </el-form-item>
      <el-form-item label="计划编号">
        <div class="my-show-span">{{ form.scheduleCode }}</div>
      </el-form-item>
      <el-form-item label="类型">
        <dict-tag class="my-show-span" :options="getScheduleSource"
                  :value="form.proSchedule ? form.proSchedule.scheduleSourceType : ''"
        />
      </el-form-item>
      <el-form-item label="产品名称">
        <div class="my-show-span">{{ form.gbsGood ? form.gbsGood.pdName : '' }}</div>
      </el-form-item>
      <el-form-item label="产品编号">
        <div class="my-show-span">{{ form.gbsGood ? form.gbsGood.pdCode : '' }}</div>
      </el-form-item>
      <el-form-item label="规格型号">
        <div class="my-show-span">{{ form.gbsGood ? form.gbsGood.pdSpecType : '' }}</div>
      </el-form-item>
      <el-form-item label="产品类型">
        <div class="my-show-span">{{ form.gbsGood ? form.gbsGood.gbsGoodClass.gcName : '' }}</div>
      </el-form-item>
      <el-form-item label="单位">
        <div class="my-show-span">{{ form.gbsGood ? form.gbsGood.gbsGoodUnit.guName : '' }}</div>
      </el-form-item>
      <el-form-item label="BOM">
        <div class="my-show-span">{{ form.workOrderBom }}</div>
      </el-form-item>
      <el-form-item label="版本">
        <div class="my-show-span">{{ form.workOrderBVersion }}</div>
      </el-form-item>
      <el-form-item label="计划数量">
        <div class="my-show-span">{{ form.workOrderNum }}</div>
      </el-form-item>
      <el-form-item label="需求日期">
        <div class="my-show-span">{{ form.proSchedule ? form.proSchedule.scheduleRequire : '' }}</div>
      </el-form-item>
      <el-form-item label="计划开工时间" prop="workOrderStart">
        <el-date-picker clearable
                        v-model="form.workOrderStart"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择完工时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划完工时间" prop="workOrderEnd">
        <el-date-picker clearable
                        v-model="form.workOrderEnd"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择完工时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" class="my-desc">
        <el-input v-model="form.workOrderDesc" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3 }"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">物料清单</div>
    </el-divider>
    <el-table
      :data="gbsBomMaterials"
    >
      <el-table-column
        type="index"
        align="center"
        label="序号"
      />
      <el-table-column label="物料编码" align="center" prop="gbsMaterial.pdCode" />
      <el-table-column label="物料名称" align="center" prop="gbsMaterial.pdName" />
      <el-table-column label="规格型号" align="center" prop="gbsMaterial.pdSpecType" />
      <el-table-column label="单位" align="center" prop="gbsMaterial.gbsGoodUnit.guName" />
      <el-table-column label="预计使用量" align="center" prop="bmUse" />
    </el-table>

    <el-divider>
      <div class="my-divider">工艺路线</div>
    </el-divider>
    <el-descriptions :column="2">
      <el-descriptions-item label="工艺路线名称">{{ form.workOrderRouteName }}</el-descriptions-item>
      <el-descriptions-item label="工艺路线编号">{{ form.workOrderRoute }}</el-descriptions-item>
    </el-descriptions>
    <el-tabs v-if="pbsProcedureRoutes && pbsProcedureRoutes.length > 0">
      <el-tab-pane v-for="(tab, index) in pbsProcedureRoutes"
                   :key="tab.ppProcedureCode"
                   :label="tab.ppProcedureCode"
      >
          <span slot="label">
            <MyTabPaneLabel :prefix-num="index + 1" :content="tab.pbsProcedure.procedureName" />
          </span>
        <el-button type="primary" @click="handleToAddTask(tab)">添加</el-button>
        <el-table :data="tab.proWorkTasks">
          <el-table-column type="index" align="center" label="序号" />
          <el-table-column label="任务名称" align="center" prop="wtaskName" />
          <el-table-column label="生产单元" align="center" prop="wtaskCell" />
          <el-table-column label="生产单元编号" align="center" prop="wtaskCell">
            <template slot-scope="scope">
              {{ getWorkCellName(scope.row.wtaskCell) }}
            </template>
          </el-table-column>
          <el-table-column label="计划数量" align="center" prop="wtaskNum" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                v-hasPermi="['gbs:bom:query']"
                @click="handleQueryMaterial(tab.selectedMaterial)"
              >查看物料
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-hasPermi="['gbs:bom:edit']"
                @click="handleToEditTask(tab, scope.row, scope.$index)"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-hasPermi="['gbs:bom:remove']"
                @click="handleRemoveTask(tab, scope.$index)"
              >移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-empty v-else description="该工艺路线还未配置工序" />

    <!--    查看工序使用的物料-->
    <el-dialog title="物料清单" :visible.sync="materialDialogVisible" width="50%" append-to-body>
      <el-table
        :data="gbsProcedureMaterials"
      >
        <el-table-column type="index" align="center" label="序号" />
        <el-table-column label="物料编号" align="center" prop="pdCode" />
        <el-table-column label="物料名称" align="center" prop="pdName" />
        <el-table-column label="规格型号" align="center" prop="pdSpecType" />
        <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName" />
        <el-table-column label="使用量" align="center" prop="procudereMNum" />
      </el-table>
    </el-dialog>

    <!-- 添加或修改工单任务对话框 -->
    <el-dialog :title="taskTitle" :visible.sync="taskDialogVisible" width="360px" append-to-body>
      <el-form ref="taskForm" :model="taskForm" :rules="taskRules" label-width="90px" label-position="left">
        <el-form-item label="任务名称" prop="wtaskName">
          <el-input v-model="taskForm.wtaskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="生产单元" prop="wtaskCell">
          <el-cascader
            v-model="taskForm.wtaskCell"
            :options="workCellOptions"
            :props="workCellProps"
            :show-all-levels="false"
            style="width: 205px"
          />
        </el-form-item>
        <el-form-item label="计划数量" prop="wtaskNum">
          <el-input-number v-model="taskForm.wtaskNum" placeholder="请输入计划数量" />
        </el-form-item>
        <el-form-item label="计划开工时间" prop="wtaskStart">
          <el-date-picker clearable
                          v-model="taskForm.wtaskStart"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划开工时间"
          />
        </el-form-item>
        <el-form-item label="计划完工时间" prop="wtaskEnd">
          <el-date-picker clearable
                          v-model="taskForm.wtaskEnd"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划完工时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTaskForm">确 定</el-button>
        <el-button @click="cancelTask">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 提交按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />
  </div>
</template>

<script>
import MyTabPaneLabel from '@/components/MyTabPaneLabel/index.vue'
import { getWorkOrder, updateWorkOrder } from '@/api/yyj/pro/workOrder'
import { listWorkCell } from '@/api/yyj/pbs/workCell'
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'

export default {
  name: 'WorkOrderChange',
  components: { MyConfirmBtnGroup, MyTabPaneLabel },
  dicts: ['yyj_schedule_source'],
  data() {
    return {
      backPage: '/pro/workOrder',
      taskTitle: '',
      taskDialogVisible: false,
      materialDialogVisible: false,
      workOrderCode: '',
      treeLoading: false,
      // 生产单元树选项
      workCellOptions: [],
      workCellList: [],
      workCellProps: {
        label: 'workCellName',
        value: 'workCellCode',
        children: 'children',
        emitPath: false,
        checkStrictly: true
      },
      form: {},
      rules: {
        workOrderStart: [
          { required: true, message: '计划开工时间不为空', trigger: 'blur' }
        ],
        workOrderEnd: [
          { required: true, message: '计划完工时间不为空', trigger: 'blur' }
        ]
      },
      taskForm: {},
      taskRules: {},
      // bom对应的物料清单
      gbsBomMaterials: [],
      gbsProcedureMaterials: [],
      // 当前工艺路线工序
      pbsProcedureRoutes: [],
      // 当前的tab
      currentTab: {},
      // 当前表格下标
      currentIndex: -1
    }
  },
  computed: {
    getScheduleSource() {
      return this.dict.type.yyj_schedule_source
    }
  },
  created() {
    this.workOrderCode = this.$route.params.workOrderCode
    this.getDetail(this.workOrderCode)
  },
  methods: {
    // 获取工单任务详情
    async getDetail(workOrderCode) {
      const res = await getWorkOrder(workOrderCode)
      this.form = res.data
      this.gbsBomMaterials = res.gbsBomMaterials
      this.pbsProcedureRoutes = res.pbsProcedureRoutes
    },
    /** 查询生产单元下拉树结构 */
    async getTreeselect() {
      const res = await listWorkCell()
      this.workCellList = res.data
      this.workCellOptions = this.handleTree(res.data, 'workCellCode', 'workCellFid')
    },
    // 去添加任务
    handleToAddTask(tab) {
      this.currentIndex = -1
      this.currentTab = tab
      console.log('tab ', tab)
      this.taskTitle = '新增工单任务'
      this.taskForm.wtaskName = tab.pbsProcedure.procedureName + '任务'
      this.taskForm.wtaskWoCode = this.workOrderCode
      this.taskForm.wtaskRouteCode = this.form.workOrderRoute
      this.taskForm.wtaskProcedureCode = tab.ppProcedureCode
      this.taskForm.wtaskStatus = '0'
      this.taskForm.wtaskBom = this.form.workOrderBom
      this.taskForm.wtaskBomVersion = this.form.workOrderBVersion
      this.taskForm.wtaskSort = tab.ppSort
      this.taskForm.wtaskCalcType = tab.ppCalcType
      this.taskForm.wtaskCalcSingle = tab.ppCalcSingle
      this.getTreeselect()
      this.taskDialogVisible = true
    },
    // 查看物料
    handleQueryMaterial(materials) {
      console.log(materials)
      this.gbsProcedureMaterials = materials
      this.materialDialogVisible = true
    },
    // 去修改任务
    handleToEditTask(tab, row, index) {
      this.currentIndex = index
      this.taskTitle = '修改工单任务'
      this.currentTab = tab
      this.taskForm = { ...row }
      this.getTreeselect()
      this.taskDialogVisible = true
    },
    // 移除任务
    handleRemoveTask(tab, index) {
      tab.proWorkTasks.splice(index, 1)
    },
    // 获取生产单元名
    getWorkCellName(workCellCode) {
      const workCell = this.workCellList.find(e => e.workCellCode === workCellCode)
      if (workCell) {
        return workCell.workCellName
      }
      return ''
    },
    // 取消提交 task
    cancelTask() {
      this.taskDialogVisible = false
      this.resetTask()
    },
    // taskForm 表单重置
    resetTask() {
      this.taskForm = {
        wtaskCode: null,
        wtaskQcPeo: null,
        wtaskWoCode: null,
        wtaskName: null,
        wtaskManager: null,
        wtaskGroup: null,
        wtaskCell: null,
        wtaskNum: null,
        wtaskStart: null,
        wtaskEnd: null,
        wtaskProcedureCode: null,
        wtaskRouteCode: null,
        wtaskStatus: null,
        wtaskPCloseReason: null,
        wtaskPDesc: null
      }
      this.resetForm('taskForm')
      this.currentTab = {}
    },
    // 提交 task
    submitTaskForm() {
      if (this.currentIndex >= 0) {
        this.currentTab.proWorkTasks.splice(this.currentIndex, 1)
      }
      if (!this.currentTab.proWorkTasks) {
        this.currentTab.proWorkTasks = []
      }
      this.currentTab.proWorkTasks.push({ ...this.taskForm })
      this.cancelTask()
    },
    // 提交生产工单排产
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (!this.pbsProcedureRoutes || this.pbsProcedureRoutes.length <= 0) {
            this.$modal.msgError('请安排任务')
            return
          }
          this.$modal.loading('正在提交...')
          const proWorkTasks = []
          this.pbsProcedureRoutes.forEach(e => {
            if (e.proWorkTasks && e.proWorkTasks.length > 0) {
              proWorkTasks.push(...e.proWorkTasks)
            }
          })
          await updateWorkOrder({
            proWorkOrder: this.form,
            proWorkTasks
          })
          this.$modal.msgSuccess('排产成功')
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
@import "@/assets/styles/yyj/change";
</style>
